<!-- Markdown 渲染 Panel -->
<template>
  <div class="flex justify-content-center">
    <ProgressSpinner v-if="loading && showLoading"
                     strokeWidth="8"
                     fill="var(--surface-ground)"
                     animationDuration=".5s"/>
  </div>
  <div class="vditor-reset"
       ref="vditorPreview"></div>
</template>

<script lang="ts" setup>
/** JS */
import {defineProps, nextTick, onMounted, reactive, ref, watch, defineEmits} from 'vue';
import Vditor from "vditor";
/** 组件 */
import ProgressSpinner from 'primevue/progressspinner';

const props = defineProps({
  markdown: {
    type: String,
    required: true
  },
  after: {
    type: Function,
    required: false
  },
  showLoading: {
    type: Boolean,
    default: false
  }
});
const emits = defineEmits(['after']);
const renderValues = reactive({
  markdown: props.markdown,
  after: props.after
});
const loading = ref(true), vditorPreview = ref(null);
const render = () => {
  if (vditorPreview.value) Vditor.preview(vditorPreview.value, renderValues.markdown, {
    mode: "dark",
    anchor: 0,
    cdn: 'https://cdn.yeziji.xyz/vditor@3.8.15',
    hljs: {
      style: 'native',
      lineNumber: true
    },
    after: () => {
      // 更新图片大小的细节
      let imgs = document.getElementsByTagName('img');
      let pattern = /{{\d+,(\s)*\d+}}/;
      if (imgs && imgs.length > 0) {
        for (let img of imgs) {
          let imgParentEle = img.parentElement;
          if (imgParentEle) {
            let innerHtml = imgParentEle.innerHTML
            if (pattern.test(innerHtml)) {
              let matchs = innerHtml.match(pattern);
              if (matchs) {
                for (let match of matchs) {
                  if (match.trim() !== '') {
                    // 获取高度进行筛选过滤
                    let matchStr = match.replace('{{', '').replace('}}', ''), matchArr = matchStr.split(',');
                    let height = matchArr[1], width = matchArr[0];
                    // 赋值 style
                    img.style.height = `${height}px`;
                    img.style.width = `${width}px`;
                    // 清除 {{number, number}}
                    imgParentEle.innerHTML = imgParentEle.innerHTML.replace(match, '');
                  }
                }
              }

            }
          }
        }
      }
      loading.value = false;
      if (renderValues.after) {
        renderValues.after();
      }
      emits('after', vditorPreview.value);
    }
  });
}

watch(props, (n, o) => {
      Object.assign(renderValues, n);
      render();
    }, {deep: true}
);

onMounted(() => {
  if (!renderValues.markdown) loading.value = true;
  else render();
})

</script>

<style scoped>

</style>
